<!-- 订单购买页 -->
<template>
  <div>

    <div v-if="!isWeixin" class="nav-title">优一家商城</div>

    <section v-if="!isWeixin || isAuth == 1" style="padding-bottom: 50px;">
      <div class="banner-area">
        <img src="../../assets/img/index_banner1.jpg" class="banner-img" alt="">
        <div class="banner-desc">
          <div>闯过三关，名牌商品寄到家</div>
          <div>闯关失败，还奖励等额积分</div>
        </div>
        <div class="gou-ins" @click="showGouIns = true;">
          闯关购说明
        </div>
      </div>

      <div class="brands-list">
        <van-grid>
          <van-grid-item v-for="item in brandsList" @click="chooseBrand(item)" :class="{ 'active': currBrand == item.id,'brands-item':true}">
            {{item.name}}
          </van-grid-item>
        </van-grid>
      </div>
      <van-tabs :animated="true" :swipeable="true" v-model="active"  @change="tabClick" @click="tabClick" :sticky="true">
        <van-tab v-for="item in categoryList" :title="item.name" :name="item.id" :data-status="item.id">
          <template>
            <van-list
              v-model="loading"
              :finished="finished"
              @load="onLoad"
              loading-text="正在加载..."
            >
              <template v-for="item in list">
                <van-card @click="goDetail(item);"
                          tag="查看商品详情"
                          :price="item.nowPrice"
                          :desc="item.buyNum+'人参与'"
                          :title="item.title"
                          :thumb="item.picName.indexOf('http')!=-1?item.picName:downloadUrl+'?fileName='+item.picName"
                >

                  <div slot="tags">
                    <van-tag v-if="item.isFav ==0" @click.stop="addFav(item);" style="background: #fff;"  plain type="danger">收藏</van-tag>
                    <van-tag v-if="item.isFav ==1"  style="background: #fff;" disabled  plain type="default">已收藏</van-tag>
                  </div>

                  <div slot="footer">
                    <div style="display: flex;justify-content: flex-end;margin-top: 5px;">
                      <div class="kh_pic" style="margin-right: 5px;background: #fff;color: #323233;border: 1px solid #ebedf0;" @click.stop="goIntegral(item);">{{item.integral}}积分兑换</div>
                      <div class="kh_pic" @click.stop="goGame(item);">{{item.gameNum}}元闯关购</div>
                    </div>

                    <!--<van-button size="mini" type="danger">购买</van-button>-->
                  </div>
                </van-card>

              </template>

              <template v-if="finished && list.length==0">
                <div class="error-info">
                  <div>
                    <img src="../../assets/img/yiyenodata.png"/>
                  </div>
                  <div class="error">该品类暂无商品~</div>
                </div>

              </template>
            </van-list>
          </template>
        </van-tab>
      </van-tabs>

      <div class="weui-loadmore weui-loadmore_line" v-if="finished && list.length!=0 && page>1">
        <span class="weui-loadmore__tips">{{loadMsg}}</span>
      </div>



      <van-tabbar v-model="active">
        <van-tabbar-item name="home" @click="goHome();" icon="wap-home">首页</van-tabbar-item>
        <van-tabbar-item name="user" @click="goUrl('/user');"  icon="contact">个人中心</van-tabbar-item>
        <van-tabbar-item name="cart" @click="goUrl('/kefu');" icon="chat-o">联系客服</van-tabbar-item>

      </van-tabbar>
    </section>
    <reCharge v-if="showRecharge" :goodsId="currGoodsId" :amount="amount" @close="showRecharge = false;"></reCharge>

    <div v-if="isWeixin" class="share-btn" @click="yd = true;">
      <div>分享</div>
      <div>好友</div>
    </div>

    <div class="free-exep" @click="goExper();">
      <div>免费</div>
      <div>体验</div>
    </div>

    <!--begin引导分享-->
    <div class="mask" v-if="yd" v-cloak></div>
    <div class="yd-pop" v-if="yd" v-cloak>
      <div class="yd-content">
        <img src="../../assets/img/fx_yd.png" />
        <div class="yd-txt">
          <div>点击右上角【 . . . 】分享给好友</div>
          <div><span style="color:#e2ef0a;">赚好运气</span></div>
        </div>
      </div>
      <img class="yd-btn" @click="yd = false;" src="../../assets/img/jk_wzd.png" />
    </div>
    <!--end引导分享-->

    <van-dialog
      v-model="showGouIns"
      title=""
      confirmButtonText="我知道了，去闯关"
    >
      <div style="font-size: 18px;text-align: center;font-weight: bold;margin-top: 5px;color: #f44;" class="rule-title">闯关购活动规则</div>
      <div class="rule">
        <h3>1、活动规则</h3>
        <h4>1）活动开始前选择您喜欢的商品；</h4>
        <h4>2）每关只需将所显示的口红插满圆盘，即可过关；</h4>
        <h4>3）连闯三关就可以获得心仪的商品；</h4>
        <h4>5）获得商品后，到个人中心-》我的奖品-》领取商品-》选择对应颜色尺码以及填写您的收货地址，我们会以快递的形式将您中奖的商品寄给您</h4>
        <h3>2、闯关失败</h3>
        <h4>1）闯关失败将获得等额积分奖励</h4>
        <h4>2）积分可以用来兑换任意商品</h4>
        <h3>3、快递说明</h3>
        <h4>一般情况下，你闯关得到的商品提交订单后48小时内我们会为您安排发货，如有特殊情况，请联系客服；</h4>
        <h3>4、注意事项</h3>
        <h4>1）当积分达到某商品的兑换条件时您将不必在玩闯关活动，直接用积分兑换即可</h4>
        <h4>2）如果闯关成功，系统将会清空您之前奖励的积分，所以积分达到可以兑换您心仪的商品时请先兑换商品哟~</h4>

      </div>
    </van-dialog>
  </div>
</template>
<script>
  import wx from 'weixin-js-sdk';
  import goodsService from '../../api/goodsService';
  import customerService from '../../api/customerService';
  import commonService from '../../api/commonService';
  import util from '../../../../../static/mobile/js/util';
  import Api from '../../api/api';
  import {Dialog} from 'vant';
  import reCharge from '../commonComponents/reCharge';
  export default {
    name:'index',
    components: {
      reCharge
    },
    data() {
      return {
        currGoodsId:'',
        yd:false,
        currBrand:'',
        winHeight:'',
        showGouIns:false,
        categoryId:'',
        active:'home',
        brandsList:[{id:'',name:'品牌'}],
        categoryList:[{id:'',name:"全部"}],
        amount:'',
        showRecharge:false,
        isAuth:'',
        isWeixin:false,
        downloadUrl:Api.download,
        active:'home',
        datalist: [],
        list: [],
        loading: false,
        finished: false,
        loadMsg: '暂无数据',
        totalPage: '',
        page: 1
      }
    },
    methods: {
      wxready: function(){
        var self = this;
        commonService.getJssdk({url:window.location.href}).then(function (rsp) {
          if(rsp.result) {
            var data = rsp.obj;
            wx.config({
              debug: false,
              async:true,
              appId: data.appId,
              timestamp: data.timestamp,
              nonceStr: data.nonceStr,
              signature: data.signature,
              jsApiList: [
                // 所有要调用的 API 都要加到这个列表中
                'onMenuShareTimeline',
                'onMenuShareAppMessage',
                'hideOptionMenu',
                'showOptionMenu',
                'checkJsApi'
              ]
            });
            wx.ready(function () {
              self.registerWXSDK();
            });
          }else{
            self.$toast(rsp.msg);
          }

        })
          .catch(function (error) {
            self.$toast('getJssdk接口异常'+error);
          });
      },
      registerWXSDK: function(){
        var self = this;
        wx.onMenuShareAppMessage({
          title: '闯关赢商品',
          desc: '只需5元就有机会赢得名牌运动鞋，点击立即参与',
          link: 'http://youyijiashop.com', //
          imgUrl: 'http://youyijiashop.com/wechat/static/img/no_login_ewm.0c0fb04.png', // 分享图标
          success: function () {
            // 用户确认分享后执行的回调函数，微信取消分享成功回调
            //self.deductCards(self.shareCard.send_id);
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        });

        wx.onMenuShareTimeline({
          title: '闯关赢商品',
          desc: '5元就有机会赢名牌运动鞋',
          link: window.location.href, //
          imgUrl: 'http://youyijiashop.com/wechat/static/img/no_login_ewm.0c0fb04.png', // 分享图标
          success: function () {
            //微信取消分享成功回调
            //self.deductCards(self.shareCard.send_id);
          },
          cancel: function () {
            // 用户取消分享后执行的回调函数
          }
        });
      },
      goExper(){
        var execUrl = window.location.origin + window.location.pathname+'?winHeight='+this.winHeight+'&vt='+new Date().getTime() + '#/gameExper';
        window.location.replace(execUrl);
      },
      addFav(item) {
        goodsService.addFav({goodsId:item.id}).then((rsp)=>{
          if(rsp.result) {
            item.isFav = 1;
          this.$toast('收藏成功，请到个人中心-》我的收藏查看');
          }else {
            this.$toast(rsp.errorMsg);
          }
        }).catch((error)=>{
            this.$toast('addFav接口异常'+error);
        });
      },
      goIntegral(item){
        customerService.getCustomerInfo().then((rsp)=>{
          if(rsp.result) {
          let customer = rsp.obj;
          if(customer.integral < item.integral) {
            Dialog.alert({
              message: '您目前剩余'+customer.integral+'积分，不足以兑换该商品哟~',
              confirmButtonText:'我知道了'
            }).then(() => {
            });

          }else {
            this.$nocacheRouter('/goodsDetailGet?id='+item.id+'&isJf=1');
          }
        }else {
          if(rsp.errorCode != '101') {
            this.$toast(rsp.errorMsg);
          }
        }
      }).catch((error)=>{
          this.$toast('getCustomerInfo接口异常'+error);
      });
      },
      goGame(item) {
        Dialog.confirm({
          messageAlign:'left',
          title: '闯关提示',
          message: '<span style="color: #f44;">闯关将消耗'+item.gameNum+'金币；闯过三关即可赢得该商品；闯关失败将获取'+item.gameNum+'积分，积分可以用来兑换商品</span>',
          confirmButtonText:'马上去闯关',
          cancelButtonText:'在看看'
        }).then(() => {
          this._judgeMoney(item);
      }).catch(() => {
        });
      },
      _judgeMoney(item) {
        goodsService.judgeMoney({goodsId:item.id}).then((rsp)=>{
          if(rsp.result) {
          if(rsp.errorCode == 2){
            this.amount = rsp.obj;
            Dialog.confirm({
              title: '提示',
              message: '您的余额不足',
              confirmButtonText:'去充值'
            }).then(() => {
              this.currGoodsId = item.id;
            this.showRecharge = true;
          }).catch(() => {
            });
            //满足积分购买
          }else if(rsp.errorCode == 3){
            Dialog.alert({
              title: '提示',
              message: '您的积分已经可以兑换该商品，无需在闯关'
            }).then(() => {
              // on close
            });
          }else {
            var srcurl = window.location.origin + window.location.pathname+'?winHeight='+this.winHeight+'&vt='+new Date().getTime() + '#/game?goodsId='+item.id+'&num='+item.gameNum;
            window.location.replace(srcurl);
            // this.$nocacheRouter('/game?goodsId='+item.id);
          }
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('judgeMoney接口异常'+error);
      });
      },

      authLogin() {
        window.location.href = Api.wechatLogin;
      },
      goUrl(url) {
        this.$nocacheRouter(url);
      },
      goDetail(item) {
        var url = window.location.origin + window.location.pathname+'?vt='+new Date().getTime() + '#/goodsDetail?id='+item.id+'&isFav='+item.isFav;
        window.location.href = url;
      },
      goHome() {
        var url = window.location.origin + window.location.pathname+'?vt='+new Date().getTime() + '#/index?auth=1';
        window.location.href = url;
      },
      tabClick(categoryId){
        this.categoryId = categoryId;
        this._resetList();
      },
      chooseBrand(item) {
        this.currBrand = item.id;
        this._resetList();
      },
      _resetList() {
        this.finished = true;
        this.$nextTick(function(){
          this.page = 1;
          this.loading = false;
          this.finished = false;
          this.datalist = [];
          this.list = [];
        });

      },

      onLoad() {
        var that = this;
        if(this.timer) {
          clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
          that.getList();
      }, CONSTANT.LIST_TIMEOUT);
      },
      getList() {
        goodsService.goodsListByGrade({currPage:this.page,pageSize:10,categoryId:this.categoryId,brandsId:this.currBrand}).then((rsp)=>{
          if(rsp.result) {
          this.loading = false;
          this.list = this.list.concat(rsp.obj.goodsList);
          var totalPage = rsp.obj.totalPage;
          if ((this.page + 1) > totalPage) {
            this.finished = true;
            this.loadMsg = '我是有底线的';
          }else {
            this.page = this.page + 1;
          }
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('goodsListByGrade接口异常'+error);
      });
      },
      getAlllAddOn() {
        goodsService.getAlllAddOn().then((rsp)=>{
          this.winHeight = window.innerHeight;
        if(rsp.result) {
          this.categoryList = this.categoryList.concat(rsp.obj);
          // if(this.categoryList.lenght>0) {
          //   this.categoryId = this.categoryList[0].id;
          // }
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('getAlllAddOn接口异常'+error);
      });
      },
      getBrandsAddOn(){
        goodsService.getBrandsAddOn().then((rsp)=>{
          if(rsp.result) {
          this.brandsList = this.brandsList.concat(rsp.obj);
        }else {
          this.$toast(rsp.errorMsg);
        }
      }).catch((error)=>{
          this.$toast('getBrandsAddOn接口异常'+error);
      });
      }
    },

    mounted(){
      var isAuth = this.$route.query.auth;
      this.isAuth = isAuth;
      this.isWeixin = util.is_weixn();
      if(isAuth !=1 && this.isWeixin) {
        this.authLogin();
        return;
      }
      if(this.isWeixin) {
        this.wxready();
      }
      this.getAlllAddOn();
      this.getBrandsAddOn();
    }
  };
</script>
<style scoped>

  .nav-title {
    height: 40px;
    line-height: 40px;
    background: rgb(255, 255, 255);
    text-align: center;
    font-weight: bold;
    font-size: 16px;
  }
  .rule {
    font-size: 11px;
    color: #f44;
    max-height: 240px;
    overflow-y: auto;
    padding-left: 0.2rem;
    padding-right: 0.2rem;
  }

  .rule h3 {
    margin-top: 8px;
    margin-bottom: 8px;
  }

  .rule h4 {
    margin-top: 4px;
    margin-bottom: 4px;
  }

  .banner-area {
    position: relative;
  }
  .banner-img {
    width: 7.5rem;
    height: 2.86rem;
  }

  .gou-ins {
    position: absolute;
    right: 10px;
    bottom: 14px;
    color: #fff;
    font-size: 16px;
    padding: 3px 8px;
    border-radius: 5px;
    background: linear-gradient(to right, #fb7d7d, #F44);
  }

  .banner-desc {
    color: #fff;
    font-size: 12px;
    position: absolute;
    bottom: 10px;
    left: 15px;
  }
  .van-tab {
    padding: 0 15px;
  }
  .free-exep {
    height:40px;
    width:40px;
    /*background:rgba(256,68,68,0.8);*/
    background: linear-gradient(to right, #F44, #fb7d7d);
    color:#fff;
    display:flex;
    flex-direction:column;
    justify-content:center;
    align-items:center;
    border-radius:100%;
    position:fixed;
    left:5px;
    bottom:60px;
    font-size:12px;
    z-index:99;
  }

  .free-exep div,.share-btn div {
    line-height: 14px;
  }

  .share-btn {
    height:40px;
    width:40px;
    /*background:rgba(256,68,68,0.8);*/
    background: linear-gradient(to right, #F44, #fb7d7d);
    color:#fff;
    display:flex;
    flex-direction:column;
    justify-content:center;
    align-items:center;
    border-radius:100%;
    position:fixed;
    left:5px;
    bottom:110px;
    font-size:12px;
    z-index:99;
  }

  .error-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-top: 1.50rem;
    text-align: center;
    margin-bottom: 0.8rem;
  }

  .error-info img{
    width: 2.85rem;
    height: 2.85rem;
  }

  .error-info .error {
    margin-top: 0.40rem;
    font-size: 0.30rem;
    color: #999;
  }

  .error-info .error div{
    font-size: 0.40rem;
  }
  .brands-list {
    margin-top: 0.2rem;
    margin-bottom: 0.2rem;
  }

  .brands-list .active {
    color: #f44;
  }

  .yd-pop {
    position: fixed;
    width: 100%;
    text-align: center;
    top: 0.2rem;
    right: 0;
    z-index: 9999;
  }

  .yd-content{
    position: relative;
  }

  .yd-txt{
    position: absolute;
    top: 2.7rem;
    color: #fff;
    font-size: 0.4rem;
    width: 100%;
  }

  .yd-content img{
    width: 6.48rem;
  }

  .yd-btn {
    width: 2.89rem;
    margin-top: 1rem;
  }

  .mask {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
    background: rgba(0,0,0,.8);
  }

</style>

<style>

  .brands-item .van-grid-item__content {
    padding: 10px 10px;
  }

  .van-icon {
    display: block;
    font-size: 24px;
  }
  .van-tabbar-item--active{
    color: #f44;
  }

  .van-card__thumb {
    width: 120px;
    height: 120px;
  }

  .van-card__title {
    font-size: 14px;
  }

  .van-card__bottom {
    font-size: 16px;
  }

  .van-card__desc {
    margin-top: 15px;
  }

  .kh_pic {
    font-size: 14px;
    color: #fff;
    border-radius: 3px;
    background: linear-gradient(to right, #fb7d7d, #F44);
    height: 0.64rem;
    line-height: 0.64rem;
    text-align: center;
    width: 2.4rem;
    box-sizing: border-box;
    margin-bottom: 10px;
  }

  .van-card {
    background: #fff;
  }

  .van-tag--danger {
    background-color: #ccc;
  }
</style>
